/**
 * Project: Duplicate Cleaner <br>
 * Package: org.leumasjaffe.operator
 */
package org.leumasjaffe.security;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.eclipse.jdt.annotation.NonNullByDefault;


/**
 * Class org.leumasjaffe.security.Checksum in file Checksum.java <br>
 * 
 * @author leumasjaffe
 * @version May 18, 2013
 * Created on: May 18, 2013
 * 
 */
@NonNullByDefault
public final class Checksum {
	private static final int BYTE_BUFFER_SIZE = 1024;

	/**
	 * 
	 */
	private Checksum() {
		
	}
	
	/**
	 * @param path
	 * @return
	 */
	public static byte[] getMD5Checksum(Path path) {
		return getChecksum("MD5", path);
	}
	
	/**
	 * @param path
	 * @return
	 */
	public static byte[] getSHA1Checksum(Path path) {
		return getChecksum("SHA-1", path);
	}
	
	/**
	 * @param path
	 * @return
	 */
	public static byte[] getSHA256Checksum(Path path) {
		return getChecksum("SHA-256", path);
	}
	
	/**
	 * @param alg
	 * @param path
	 * @return
	 */
	@SuppressWarnings("null")
	public static byte[] getChecksum(String alg, Path path) {
		MessageDigest md = null;
		byte[] digest = new byte[0];
		try {
			md = MessageDigest.getInstance(alg);
			try (InputStream is = Files.newInputStream(path);
					DigestInputStream dis = new DigestInputStream(is, md)) {
				final byte[] b = new byte[BYTE_BUFFER_SIZE];
				while (dis.read(b) == BYTE_BUFFER_SIZE){} // $codepro.audit.disable emptyWhileStatement
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		} catch (NoSuchAlgorithmException nsae) {
			nsae.printStackTrace();
		}
		finally {
			if (md != null) {
				digest = md.digest();
			}
		}
		return digest;
	}

}
